import { changeArticleStatus, deleteArticle, queryArticleList } from "@/api/content/article";
import { useCallback, useEffect, useState } from "react";
import { Article } from "../../../../types/content/article";
import { message } from "antd";
import { deleteFileInf } from "@/utils/deleteFileInf";

export const useArticleTable = () => {
  const [messageApi] = message.useMessage();
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState<Article.Row[]>([]);
  const [pagination, setPagination] = useState<Pagination>({
    pageNo: 1,
    pageSize: 10,
    total: 0,
  });
  // 搜索表单
  const [searchForm, setSearchForm] = useState<Article.Query>({
    // 文章标题
    title: "",
    // 分类名称
    categoryId: "",
    // 是否评论
    isComment: "",
    // 是否置顶
    isTop: "",
    tagIds: [],
    summary: "",
    time: ["", ""],
  });

  /**
   * 获取文章表格数据
   */
  const getArticleList = useCallback(async () => {
    const {
      title,
      categoryId,
      isComment,
      isTop,
      tagIds,
      summary,
      time,
      status,
    } = searchForm;

    const params = {
      title,
      categoryId,
      isComment,
      isTop,
      pageSize: pagination.pageSize,
      pageNo: pagination.pageNo,
      tagIds,
      summary,
      startTime: time![0] || "",
      endTime: time![0] || "",
      status,
    };
    setLoading(true);
    const res = await queryArticleList(params);
    setLoading(false);
    if (res.code === 200) {
      setTableData(res.data?.rows || []);
      setPagination({
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
        total: res.data?.total || 0,
      });
    }
  }, [pagination.pageNo, pagination.pageSize, searchForm]);
  /**
   * 删除文章
   * @param id 
   */
  const removeArticle = async (row: Article.Row) => {
    setLoading(true)
    const res = await deleteArticle({
      ids: [row.id]
    })
    setLoading(false)
    if (res.code === 200) {
      messageApi.success('删除成功')
      row.thumbnail && deleteFileInf(row.thumbnail)
      if (tableData.length === 1) {
        setPagination({
          pageNo: Math.max(1, pagination.pageNo - 1),
          pageSize: pagination.pageSize,
          total: pagination.total
        })
      } else {
        getArticleList()
      }
    }
  }
  const changeArticleStatusInf = async (id: string, status: '0' | '1') => {
    setLoading(true)
    const res = await changeArticleStatus(id, status)
    setLoading(false)
    if (res.code === 200) {
      getArticleList()
    }
  }
  useEffect(() => {
    getArticleList();
  }, [getArticleList, pagination.pageNo, pagination.pageSize, searchForm]);
  return {
    pagination,
    tableData,
    loading,
    setSearchForm,
    setPagination,
    removeArticle,
    changeArticleStatusInf
  }
}